package questions;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Administrator
 * @Date: 2023/2/8 17:03
 * 代码分析
 * 1.pop的remove会下标越界
 * 2.方法上的synchronize 和代码中的起不到双重检查 作用
 *
 * 如何改进
 * #1.将pop中的if检查改为while
 *
 */

public class MyStack {
    public static void main(String[] args) {
        final MyStack stack = new MyStack();

        for (int i = 0; i < 100; i++) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        String s = null;

                        s = stack.pop();

                        System.out.println("pop" + s);
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }
            }.start();


        }

        for (int i = 0; i < 100; i++) {
            final int finalI = i;
            new Thread() {
                @Override
                public void run() {
                    stack.push("ab" + finalI);
                }
            }.start();
        }
    }

    private List<String> list = new ArrayList<>();

    public synchronized void push(String str) {
        synchronized (this) {
            list.add(str);
            notify();
        }
    }

    public synchronized String pop() throws InterruptedException {
        synchronized (this) {
            if (list.size() < 0) {
                wait();
            }
        }
        return list.remove(list.size() - 1);
    }
}

